<template>
  <div class="form-container">
    <el-form inline :model="form" ref="ruleForm" class="form-line" label-width="60">
      <el-form-item label="姓名" prop="name">
        <el-input size="default" v-model="form.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="手机号码"></el-input>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleReset(ruleForm as FormInstance)">重置</el-button>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column fixed prop="fullName" label="姓名" />
      <el-table-column prop="phonenumber" label="手机号" />
      <el-table-column prop="mainPostName" label="主岗" />
      <el-table-column prop="assistancePostName" label="辅岗" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch active-value="0" disabled inactive-value="1" v-model="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            :disabled="scope.row.status === '0'"
            @click="handleDelete(scope.row.userId)"
            >{{ scope.row.status === "1" ? "删除" : "-----" }}</el-button
          >
          <el-button link type="primary" size="small" @click="handleEdit(scope.row.userId)"> 修改 </el-button>
          <el-button link type="primary" size="small" @click="handleUpdatePhone(scope.row)"> 修改手机号 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        size="small"
        v-model:current-page="form.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        layout="prev, pager, next"
        :total="pageTotal"
        @change="handleSearch"
        :page-size="form.pageSize"
      />
    </div>
  </div>
  <el-dialog v-model="centerDialogVisible" title="修改手机号" width="500" center>
    <div>
      <el-form :model="updatePhoneForm" ref="refPhoneForm" :rules="updatePhoneFormRules" label-width="100">
        <el-form-item prop="oldPhonenumber" label="旧手机号">
          <el-input v-model="updatePhoneForm.oldPhonenumber" disabled placeholder=""></el-input>
        </el-form-item>
        <el-form-item prop="phonenumber" label="新手机号">
          <el-input v-model="updatePhoneForm.phonenumber" placeholder="请填写新手机号"></el-input>
        </el-form-item>
        <el-form-item prop="smsCode" label="新手机验证码">
          <el-input v-model="updatePhoneForm.smsCode" placeholder="请填写短信验证码"></el-input>
          <span class="sms-code"
            ><el-button type="text" :disabled="codeTime > 0" @click="handleGetSmsCode">{{
              codeTime > 0 ? `${codeTime}秒后重新获取` : "获取验证码"
            }}</el-button></span
          >
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdatePhoneSubmit(refPhoneForm as FormInstance)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="useProTable">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getStaffListAPI, staffDeleteAPI, updatePhoneAPI } from "@/api/modules/province/organizMangeAPI";
import { Staff } from "@/api/interface/province/organizationManage";
const router = useRouter();
//ProCompanyType 已经通过declare全局申明过不用再单独导入
let tableData = ref<Staff.Row[]>([]);
let pageTotal = ref<number>(0);
let centerDialogVisible = ref<boolean>(false);
let codeTime = ref<number>(0);
const form = ref<Staff.Search>({
  province: JSON.parse(localStorage.getItem("userInfo") || "null").province,
  city: "",
  name: "",
  phone: "",
  pageNum: 1,
  pageSize: 10
});
const updatePhoneForm = ref<Staff.UpdatePhone>({
  oldPhonenumber: "",
  phonenumber: "",
  /**
   * 验证码
   */
  smsCode: "",
  /**
   * 用户ID
   */
  userId: 1
});
const ruleForm = ref<FormInstance>();
const refPhoneForm = ref<FormInstance>();
const updatePhoneFormRules = reactive<FormRules>({
  phonenumber: [
    { required: true, message: "请输入新手机号", trigger: "blur" },
    { type: "string", message: "请输入正确的手机号", trigger: "blur" }
  ],
  smsCode: [
    { required: true, message: "请输入短信验证码", trigger: "blur" },
    { type: "string", message: "请输入正确的短信验证码", trigger: "blur" }
  ]
});
const handleEdit = (id: string) => {
  router.push({
    path: "/provinceLevel/proOrganization/proStaff/add",
    query: { id }
  });
};
const handleReset = (Elform: FormInstance) => {
  Elform.resetFields();
};

const handleSearch = (): void => {
  getStaffList();
};
const handleAdd = (): void => {
  router.push("/provinceLevel/proOrganization/proStaff/add");
};
const handleDelete = (id: string): void => {
  ElMessageBox.confirm(`确定删除该条记录${id}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteStaff(id);
      getStaffList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
// 删除仓站
const deleteStaff = async (id: string) => {
  const { code, msg } = await staffDeleteAPI(id);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "删除成功!"
    });
  } else {
    ElMessage.error(`删除失败,${msg}`);
  }
};
// 列表接口请求地址
const getStaffList = async () => {
  const { rows, total, code, msg } = await getStaffListAPI(form.value);
  console.log(total, code);
  if (code == "200" && rows) {
    tableData.value = rows;
    if (total) pageTotal.value = total;
  } else {
    ElMessage.error(`获取列表失败,${msg}`);
  }
};
const handleUpdatePhone = (row: Staff.UserInfo): void => {
  updatePhoneForm.value.oldPhonenumber = row.phonenumber;
  updatePhoneForm.value.userId = row.userId as number;
  centerDialogVisible.value = true;
};
const handleGetSmsCode = () => {
  if (!updatePhoneForm.value.phonenumber) return ElMessage.error("请填写新手机号");
  codeTime.value = 60;
  let timer = setInterval(() => {
    codeTime.value--;
    if (codeTime.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};
const handleUpdatePhoneSubmit = (elForm: FormInstance) => {
  elForm.validate((valid: boolean) => {
    if (valid) {
      console.log(updatePhoneForm.value);
      // 发送请求
      updatePhone();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const updatePhone = async () => {
  delete updatePhoneForm.value.oldPhonenumber;
  console.log(updatePhoneForm.value);
  const { code, msg } = await updatePhoneAPI(updatePhoneForm.value);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "修改成功!"
    });
    getStaffList();
    centerDialogVisible.value = false;
  } else {
    ElMessage.error(`修改失败,${msg}`);
    centerDialogVisible.value = false;
  }
};
onMounted(() => {
  getStaffList();
});
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
  }
  .el-form {
    display: inline-block;
  }
  .form-line {
    .el-form-item {
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  padding: 40px 10px;
  padding-bottom: 60px;
  background-color: white;
  .pagination-container {
    // display: inline-block;
    float: right;
    margin-top: 20px;
    background-color: white;
  }
}
.sms-code {
  position: absolute;
  right: 5px;
}
::v-deep .el-form-item__label {
  font-size: 13px;
}
::v-deep .el-button > span {
  font-size: 13px;
}
::v-deep .el-input__inner {
  font-size: 13px;
}
</style>
